package com.libraryManage.commons.utils.jwt;

import cn.hutool.core.bean.BeanUtil;
import com.libraryManage.entity.ManagerDo;
import com.libraryManage.service.ManagerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * AccountRealm是shiro进行登录或者权限校验的逻辑所在，算是核心了，我们需要重写3个方法，分别是
 * supports：为了让realm支持jwt的凭证校验
 * doGetAuthorizationInfo：权限校验
 * doGetAuthenticationInfo：登录认证校验
 */
@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    ManagerService managerService;

    @Override
    public boolean supports(AuthenticationToken token) {
        //instanceof 运算符是用来在运行时判断对象是否是指定类及其父类的一个实例。
        //比较的是对象，不能比较基本类型
        //JwtToken 继承了 AuthenticationToken
        return token instanceof JwtToken;
    }

    /**
     * 获取用户权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 校验jwt信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwt = (JwtToken) token;
        log.info("jwt----------------->{}", jwt);
        //从jwt中获取用户id
        String userId = jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject();
        //查看用户状态
        ManagerDo user = managerService.getManagerById(userId);
        if(user == null) {
            throw new UnknownAccountException("账户不存在！");
        }
        if(user.getStatus() == 1) {
            throw new LockedAccountException("账户已被锁定！");
        }
        //返回用户的一些可公开的信息
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);
        log.info("profile----------------->{}", profile.toString());
        return new SimpleAuthenticationInfo(profile, jwt.getCredentials(), getName());
    }
}
